package com.uduemc.biso.node.web.api.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uduemc.biso.core.component.baidu.dto.ErnieBotRequestMessages;
import com.uduemc.biso.core.component.baidu.dto.ErnieBotResponse;
import com.uduemc.biso.core.component.baidu.dto.NodeErnieBotRequestMessages;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.custom.centerconfig.CenterConfigAiSetup;
import com.uduemc.biso.core.extities.node.custom.AiTextHistory;
import com.uduemc.biso.core.extities.node.custom.LoginNode;
import com.uduemc.biso.core.extities.node.custom.aitexthistory.AiTextHistoryMessages;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.api.ApiAiUtil;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.service.AiService;
import com.uduemc.biso.node.web.api.service.CenterService;
import com.uduemc.biso.node.web.api.service.LoginService;
import com.uduemc.biso.node.web.component.CenterFunction;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class AiServiceImpl implements AiService {

	private static final String usedAiTextDayTime = "Node:USED_AI_TEXT_DAY_TIME";

	@Autowired
	private LoginService loginServiceImpl;

	@Autowired
	private CenterService centerServiceImpl;

	@Autowired
	private CenterFunction centerFunction;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public int ai() throws IOException {
		CenterConfigAiSetup aiSetup = centerServiceImpl.getAiSetup();
		return aiSetup.getType();
	}

	@Override
	public int aiTextDayTime() throws IOException {
		CenterConfigAiSetup aiSetup = centerServiceImpl.getAiSetup();
		// 直销和代理区分
		if (loginServiceImpl.isAgent()) {
			// 代理
			int agentExperienceErnieBot = aiSetup.getAgentExperienceErnieBot();
			if (agentExperienceErnieBot == 0) {
				return 0;
			}
			Date agentExperienceErnieBotExpireDate = aiSetup.getAgentExperienceErnieBotExpireDate();
			if (agentExperienceErnieBotExpireDate != null) {
				if (DateUtil.compare(DateUtil.date(), DateUtil.date(agentExperienceErnieBotExpireDate)) > 0) {
					return 0;
				}
			}
			return aiSetup.getAgentExperienceErnieBotDayTime();
		} else {
			// 直销
			int experienceErnieBot = aiSetup.getExperienceErnieBot();
			if (experienceErnieBot == 0) {
				return 0;
			}
			Date experienceErnieBotExpireDate = aiSetup.getExperienceErnieBotExpireDate();
			if (experienceErnieBotExpireDate != null) {
				if (DateUtil.compare(DateUtil.date(), DateUtil.date(experienceErnieBotExpireDate)) > 0) {
					return 0;
				}
			}
			return aiSetup.getExperienceErnieBotDaTime();
		}
	}

	@Override
	public int usedAiTextDayTime() {
		Host host = requestHolder.getHost();
		Integer time = (Integer) redisUtil.hget(usedAiTextDayTime, String.valueOf(host.getId()));
		if (time == null) {
			return 0;
		}
		return time.intValue();
	}

	@Override
	public void addAiTextDayTime() throws IOException {
		int time = usedAiTextDayTime();
		time++;
		Host host = requestHolder.getHost();
		redisUtil.hset(usedAiTextDayTime, String.valueOf(host.getId()), time);
	}

	@Override
	public void cleanAllAiTextDayTime() throws IOException {
		redisUtil.del(usedAiTextDayTime);
	}

	@Override
	public void resetUsedAiTextDayTime(long hostId) throws IOException {
		redisUtil.hset(usedAiTextDayTime, String.valueOf(hostId), 0);
	}

	@Override
	public JsonResult aiTextHistory() {
		AiTextHistory aiTextHistory = loginNodeAiTextHistory();
		return JsonResult.ok(aiTextHistory);
	}

	@Override
	public JsonResult aiTextDialogue(String message) throws IOException {
		if (StrUtil.isBlank(message)) {
			return JsonResult.illegal();
		}

		if (StrUtil.length(message) > 2000) {
			return JsonResult.messageError("提交的文本内容不能超过2000个字符长度！");
		}

		int aiTextDayTime = aiTextDayTime();
		int usedDayTime = usedAiTextDayTime();
		if (usedDayTime >= aiTextDayTime) {
			return JsonResult.messageError("今天体验次数已用尽，欢迎明天再来体验！");
		}

		AiTextHistory aiTextHistory = loginNodeAiTextHistory();
		Long hostId = requestHolder.getHost().getId();
		String uniquid = aiTextHistory.getUniquid();
		int type = 1;

		AiTextHistoryMessages dialogue = aiTextHistory.getDialogue();
		List<NodeErnieBotRequestMessages> history = dialogue.getHistory();
		if (history == null) {
			history = new ArrayList<>();
		}

		List<ErnieBotRequestMessages> listErnieBotRequestMessages = ApiAiUtil.makeErnieBotRequestMessagesList(history);
		listErnieBotRequestMessages.add(new ErnieBotRequestMessages("user", message));

		ErnieBotResponse ernieBot = centerFunction.ernieBot(hostId, type, uniquid, listErnieBotRequestMessages);
		String result = null;
		if (ernieBot == null) {
			// 返回的结果为空，提示无返回信息。
			result = "获取信息失败，请联系管理员。";
		} else {
			addAiTextDayTime();
			result = ernieBot.getResult();
		}

		boolean need_clear_history = ernieBot.isNeed_clear_history();

		NodeErnieBotRequestMessages lastUser = new NodeErnieBotRequestMessages("user", message, need_clear_history);
		history.add(lastUser);
		dialogue.setLastUser(lastUser);

		NodeErnieBotRequestMessages lastAssistant = new NodeErnieBotRequestMessages("assistant", result, need_clear_history);
		history.add(lastAssistant);
		dialogue.setLastAssistant(lastAssistant);

		dialogue.setHistory(history);
		loginServiceImpl.recacheLoginNode();

		return JsonResult.ok(loginNodeAiTextHistory());
	}

	@Override
	public JsonResult aiTextWriting(String content) throws IOException {
		return aiTextWriting("", content);
	}

	@Override
	public JsonResult aiTextWriting(String way, String content) throws IOException {

		if (StrUtil.isBlank(way)) {
			way = "撰写优化";
		}

		if (StrUtil.isBlank(content)) {
			return JsonResult.illegal();
		}

		if (StrUtil.length(content) > 2000) {
			return JsonResult.messageError("提交的文本内容不能超过2000个字符长度！");
		}

		int aiTextDayTime = aiTextDayTime();
		int usedDayTime = usedAiTextDayTime();
		if (usedDayTime >= aiTextDayTime) {
			return JsonResult.messageError("今天体验次数已用尽，欢迎明天再来体验！");
		}

		AiTextHistory aiTextHistory = loginNodeAiTextHistory();
		Long hostId = requestHolder.getHost().getId();
		String uniquid = aiTextHistory.getUniquid();
		int type = 2;

		AiTextHistoryMessages writing = aiTextHistory.getWriting();
		List<NodeErnieBotRequestMessages> history = writing.getHistory();
		if (history == null) {
			history = new ArrayList<>();
		}

		List<ErnieBotRequestMessages> messages = new ArrayList<>();
		messages.add(new ErnieBotRequestMessages("user", "对下列内容" + way + "：\\n" + content));
		ErnieBotResponse ernieBot = centerFunction.ernieBot(hostId, type, uniquid, messages);
		String result = null;
		if (ernieBot == null) {
			// 返回的结果为空，提示无返回信息。
			result = "获取信息失败，请联系管理员。";
		} else {
			addAiTextDayTime();
			result = ernieBot.getResult();
		}

		boolean need_clear_history = ernieBot.isNeed_clear_history();

		NodeErnieBotRequestMessages lastUser = new NodeErnieBotRequestMessages("user", content, need_clear_history);
		history.add(lastUser);
		writing.setLastUser(lastUser);

		NodeErnieBotRequestMessages lastAssistant = new NodeErnieBotRequestMessages("assistant", result, need_clear_history);
		history.add(lastAssistant);
		writing.setLastAssistant(lastAssistant);
		writing.setHistory(history);

		loginServiceImpl.recacheLoginNode();

		return JsonResult.ok(loginNodeAiTextHistory());
	}

	protected AiTextHistory loginNodeAiTextHistory() {
		LoginNode loginNode = requestHolder.getCurrentLoginNode();
		AiTextHistory aiTextHistory = loginNode.getAiTextHistory();
		if (aiTextHistory == null) {
			aiTextHistory = new AiTextHistory();
			aiTextHistory.setUniquid(IdUtil.getSnowflakeNextIdStr());
			loginNode.setAiTextHistory(aiTextHistory);

			loginServiceImpl.recacheLoginNode(loginNode);
		}
		return aiTextHistory;
	}

}
